#include <stdio.h>
#include <stdlib.h>
#include "dbg.h"
#define STACKSIZE 5

typedef struct _stack {
    int size;
    int index;
    int data[STACKSIZE];
} stack;

stack *stack_init()
{
    stack *s = (stack *)malloc(sizeof(struct _stack));
    check(s, "init stack failed.");
    s->size = STACKSIZE;
    s->index = 0;

    return s;
error:
    return NULL;
}

void stack_destory(stack *s)
{
    if(s != NULL)
        free(s);
}

void stack_push(stack *s, int value)
{
    if(s == NULL) return;

    if(s->index == s->size)
    {
        printf("stack overflow!\n");
        return;
    }

    s->data[s->index] = value;
    s->index++;
}

void stack_pop(stack *s)
{
    if(s == NULL) return;

    if(s->index > 0) s->index--;
}

int *stack_current(stack *s)
{
    if(s == NULL || s->index == 0) return NULL;

    return &s->data[s->index - 1];
}

void stack_print(stack *s)
{
    if(s == NULL || s->index == 0)
    {
        printf("s is an empty stack\n");
        return;
    }

    int i;
    printf("====");
    for(i = s->index - 1; i >= 0; i--)
    {
        printf("%4d", s->data[i]);
    }
    printf("====\n");
}

int main(int argc, char *argv[])
{
    stack *s = stack_init();
    stack_push(s, 5);
    check(*stack_current(s) == 5, "Except 5, but was %d\n", *stack_current(s));
    stack_push(s, 4);
    stack_pop(s);
    stack_push(s, 3);
    stack_push(s, 1);
    check(*stack_current(s) == 1, "Except 1, but was %d\n", *stack_current(s));
    stack_print(s);
    stack_push(s, 3);
    stack_push(s, 1);
    stack_push(s, 1);
    stack_push(s, 1);
    stack_destory(s);

    return 0;
error:
    stack_destory(s);
    return -1;
}
